var base = $("base").attr("ul");
var rawType = $('base').attr('rawType');
var dsId = $('base').attr('dsId');
var modelId = $('base').attr('modelId');

 /** Created by Administrator on 2017/11/10.
 */
    var graph = new joint.dia.Graph;
    var paper = new joint.dia.Paper({
        width: 2000,
        height: 1500,
        model: graph,
        gridSize: 1,
        snapLinks: true,
        linkPinning: false,
        defaultLink: new joint.dia.Link({
           // router: { name: 'manhattan' },
            connector: { name: 'rounded' },
            attrs: {
                '.connection': {
                    stroke: '#20C1DD',
                    'stroke-width': 2,
                    'stroke-dasharray': '5 2',
                    pointerEvents: 'none',
                },
                '.marker-target': {
                    fill: '#20C1DD',
                    stroke: '#fff',
                    d: 'M 10 0 L 0 5 L 10 10 z'
                }
            },
        }),
    });
    //paper背景
    var bgimage = ''
    paper.drawBackground({
        image : bgimage
    });

    //控制纸张
    var paperScroller = new joint.ui.PaperScroller({
        paper: paper,
        autoResizePaper: true,
        padding: 50,
        cursor: 'grab'
    });
    // 移动纸张
    paper.on('blank:pointerdown', paperScroller.startPanning);
    $('#paper').append(paperScroller.render().el);
    paperScroller.center();    //移动到页面的中间


var commandManager = new joint.dia.CommandManager({
    graph: graph
});
var toolbar = new joint.ui.Toolbar({   //头部控制模块
    groups: {
        'undo-redo': { index: 1 },
        'clear': { index: 2 },
        'export': { index: 3 },
        'print': { index: 4 },
        'layout': { index: 5 },
        'order': { index: 6 },
        'zoom': { index: 7 },
        'fullscreen': { index: 8 },
        'grid': { index: 9 },
        'snapline': { index: 10 }
    },
    tools: [
        {
            type: 'button',
            name: 'undo',
            group: 'undo-redo',
            attrs: {
                button: {
                    'id':'btn-undo',
                    'data-tooltip': '撤销',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'redo',
            group: 'undo-redo',
            attrs: {
                button: {
                    'id':'btn-redo',
                    'data-tooltip': '返回',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'clear',
            group: 'clear',
            attrs: {
                button: {
                    id: 'btn-clear',
                    'data-tooltip': '清除',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'svg',
            group: 'export',
            text: 'Export SVG',
            attrs: {
                button: {
                    id: 'btn-svg',
                    'data-tooltip': '导出SVG',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'png',
            group: 'export',
            text: 'Export PNG',
            attrs: {
                button: {
                    id: 'btn-png',
                    'data-tooltip': '导出PNG',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'print',
            group: 'print',
            attrs: {
                button: {
                    id: 'btn-print',
                    'data-tooltip': '打印',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            group: 'layout',
            name: 'layout',
            attrs: {
                button: {
                    id: 'btn-layout',
                    'data-tooltip': '自动布局',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'zoom-to-fit',
            name: 'zoom-to-fit',
            group: 'zoom',
            attrs: {
                button: {
                    'data-tooltip': '自适应缩放',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'label',
            name: 'zoom-slider-label',
            group: 'zoom',
            text: 'Zoom:'
        },
        {
            type: 'zoom-slider',
            name: 'zoom-slider',
            group: 'zoom'
        },
        
        {
            type: 'toggle',
            name: 'toggle',
            group: 'last',
            value:true
        },

        {
            type: 'button',
            name: 'search',
            group: 'last',
            text: '搜索',
            attrs: {
                button: {
                    id: 'btn-search',
                    'data-tooltip': '搜索',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'refresh',
            group: 'last',
            text: '刷新',
            attrs: {
                button: {
                    id: 'btn-refresh',
                    'data-tooltip': '刷新',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        }
    ],
    references: {
        paperScroller: paperScroller,
        commandManager: commandManager
    }
});

if($('base').attr('rawType')!='fm'){
	var save =  {
            type: 'button',
            name: 'save',
            group: 'last',
            text: '保存',
            attrs: {
                button: {
                    id: 'btn-save',
                    'data-tooltip': '保存',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        };
	toolbar.tools.push(save);

}
$('#app').prepend(toolbar.render().el);
//中英文切换
console.log(toolbar)
toolbar.on('toggle:change', function(value, event) {

    $.each(graph.getElements(),function(i,v){
    	var cell = v;
    	var view = paper.findViewByModel(v);
    	var currentColumn = view.$el.find(".columnName");
    	 	  	 
    	 //如果是中文
    	 if(value === true){
    	
    		 cell.attributes.attrs.isEnglish = false; //是中文
    		 view.$el.find("tspan").text(cell.attributes.attrs.objectChname);
    		 $.each(currentColumn, function (i, v) {
        		 var columnchname = $(this).attr("data-columnchname");
              
                 $(this).text(columnchname);

             })
    	 }else {
    	
    		 cell.attributes.attrs.isEnglish = true; //是英文
    		 view.$el.find("tspan").text(cell.attributes.attrs.tableName);
    		 
    		 $.each(currentColumn, function (i, v) {
        		 var columnchname = $(this).attr("data-columnname");
        	
                 $(this).text(columnchname);

             })
    	 }
    	 
    	 cell.attributes.attrs.div.html = view.$el.find('.content').html();
    })
    var promptMsg = "";
	value=== true?promptMsg="已切换为中文":promptMsg = "已切换为英文";
    layer.msg(promptMsg,{time:1500})
});

paper.on('cell:pointerclick',function(cellView){
	console.log(cellView)
	$('.body').removeClass('eleHighlight');
	cellView.$el.find('.body').addClass('eleHighlight');
	
	   halo = new joint.ui.Halo({theme: 'modern', cellView: cellView});
       //元素只连接元素
	        halo.on('action:link:add', function(link) {
	            if (!link.get('source').id || !link.get('target').id) {
	                link.remove();
	            }
	        });
	        halo.removeHandle('clone');
	        halo.removeHandle('fork');
	        halo.removeHandle('unlink');
	        halo.removeHandle('remove');
	        halo.removeHandle('rotate');
	        halo.render();
/*
    //自定义中英文切换
    halo.addHandle({
        name: 'languageChange', position: 'ne', icon: '/assets/custom/draw/img/englishChange.svg', attrs: {
            '.handle': {
                'data-tooltip-class-name': 'small',
                'data-tooltip': '中英文切换',
                'data-tooltip-position': 'left'
            }
        }
    });

    //切换语言事件
    halo.on('action:languageChange:pointerdown', function (evt) {
        evt.stopPropagation();

//需要切换的元素
        var currentColumn = cellView.$el.find(".columnName");
//如果是英文且切换成中文(反之)
        if (cellView.model.attributes.attrs.isEnglish) {
            $.each(currentColumn, function (i, v) {

                var columnchname = $(this).attr("data-columnchname");
                $(this).text(columnchname);

            })
            cellView.model.attributes.attrs.isEnglish = false;

            cellView.$el.find("tspan").text(cellView.model.attributes.attrs.objectChname);

        } else {

            $.each(currentColumn, function (i, v) {

                var columnName = $(this).attr("data-columnName");
                $(this).text(columnName);
             
            });
            cellView.model.attributes.attrs.isEnglish = true;
            cellView.$el.find("tspan").text(cellView.model.attributes.attrs.tableName);
        }
//model更新
        cellView.model.attributes.attrs.div.html = cellView.$el.find('.content').html();
    });

*/
	        var sourceLink = graph.getConnectedLinks(cellView.model,{inbound : false,outbound:true });	
			   var targetLink = graph.getConnectedLinks(cellView.model,{inbound : true,outbound:false });
			   $.each(sourceLink,function(i,v){
				   
				   var sourceLinkView =  paper.findViewByModel(v.id);
				   sourceLinkView.$el.find('.connection').addClass('eleToSourceLink');
				   sourceLinkView.$el.find('.marker-target').addClass('eleToSourceLinkT');
			   })
			   
			    $.each(targetLink,function(i,v){
				   
				   var targetLinkView =  paper.findViewByModel(v.id);
				   targetLinkView.$el.find('.connection').addClass('eleToTargetLink');
				   targetLinkView.$el.find('.marker-target').addClass('eleToTargetLinkT');
			   })
	        
	        
	 
	
	if($('base').attr('rawType')=='fm'){
	     console.log(cellView);
	     halo.removeHandle('link');
	        
	}
})



    //元素间的对齐线
    var snaplines = new joint.ui.Snaplines({ paper: paper });
    snaplines.startListening();



    //halo组件
    var halo;

    //鹰眼开始
    var nav = new joint.ui.Navigator({
        paperScroller: paperScroller,
        width: 133,
        height: 100,
        padding: 5,
        model: graph,
        gridSize: 1,
//        zoomOptions: { max: 2, min: 0.12 }
    });
    nav.$el.appendTo('#myholder-small');
    nav.render();
    //小图结束

    //模板开始
/* var stencil = new joint.ui.Stencil({ graph: graph,paper: paper, width: 100,
        groups: {
            one: { label: '数据实体', index: 1 },
            two: { label: '文本', index: 2,closed:true },
            three: { label: '通用', index: 3,closed:true }
        },
        dragEndClone: function(cell) {
            var clone = cell.clone();
            var type = clone.get('type');

            // some types of the elements need resizing after they are dropped
            var sizeMultiplier = {'uml.Bulb': 1.5 }[type];

            if (sizeMultiplier) {
                var originalSize = clone.get('size');
                clone.set('size', {
                    width: originalSize.width * sizeMultiplier,
                    height: originalSize.height * sizeMultiplier
                });
            }

            return clone;
        }
    });
    $('#stencil-holder').append(stencil.render().el);

  var i = new joint.shapes.basic.Image({
    position: { x: 25, y: 15 },
    size: { width: 30, height: 30 },
    attrs: {
        image: { width: 30, height: 30, 'xlink:href': '/assets/custom/draw/img/tb.svg'}
    },
    description: 'image'

});
stencil.load({ one: [i] });
*/
    //页面添加元素时
/*graph.on('add', function(cell) {
    if(cell.attributes.type == 'basic.Image'){
        layer.open({
            type: 2,
            content: ['test.html', 'no'],
            area: ['500px', '300px'],
            maxmin: true
        });
        console.log(cell.attributes.position);
        console.log(cell.id)
        cell.remove()
    }
});*/


    //tooltip模块
    new joint.ui.Tooltip({
        target: '[data-tooltip]',
        rootTarget: document.body,
        direction: 'auto',
        padding: 15,
    });

 

    $("#app").on('click','.tool-options',function(){    //点击编辑关系线
        var id=	$(this).parents(".joint-cell").attr("model-id");
        	var link = graph.getCell(id);
        	console.log(link)
             layer.open({
                 title : '添加逻辑外键关系',
                 type: 2,
                 content: [requestUrl+'/page/modelModify/addFKRelate?objId='+link.attributes.source.id+'&referObjId='+link.attributes.target.id+'&lineId='+link.attributes.id],
                 area:  ['800px', '400px'],
                 maxmin: true
             });
         });
    
paper.on('blank:pointerclick',function(){  //单击页面时移除所有的高亮
    $('.body').removeClass('eleHighlight');
    $('.connection').removeClass('linkHighlight eleToSourceLink eleToTargetLink');
    $('.marker-target').removeClass('linkTargetHighlight eleToSourceLinkT eleToTargetLinkT')  
});

graph.on('remove', function(cell) {
    $.ajax({
        url: requestUrl+'/rest/webpage/render/deleteFK?fkId='+cell.id,
        type: 'GET',
        dataType: 'json',
        data: {"fkId ": cell.id},
        success: function (data) {
            console.log('成功');
        },
        error: function (data) {
            console.log('网络异常')
        }
    })
});

paper.on('cell:contextmenu',function(cellView,evt,x,y){


/*	console.log(cellView.model.id)

	if(cellView.model.attributes.type == "bpmn.Choreography"){
		  var e = evt || window.evt;
			$('.item_ul').remove();
			var fa_item_ul = $('<ul class="vakata-context jstree-contextmenu jstree-default-contextmenu item_ul"></ul>');
			var fa_item_li;
			if($('base').attr('rawType') == "fm"){
				fa_item_li = ['加入梳理模型','浏览数据','SQL查询'];
			}else if($('base').attr('rawType') == "cm"){
				 fa_item_li = ['浏览数据','SQL查询'];
			}else if($('base').attr('rawType') == "CLUSTING_SUB"){
				 fa_item_li = ['浏览数据','SQL查询'];
			}
			
			$.each(fa_item_li,function(i,v){
				fa_item_ul.append('<li><a href="#">'+v+'</a></li>')
			});
			var dsId = $('base').attr("dsId");
			var id = cellView.model.id;
			var qTableName = cellView.model.attributes.qTableName;
			fa_item_ul.appendTo($('#app'));
			$('.item_ul').css({'display':'block','position':'absolute','z-index':'1000','background':'#fff','left':''+(e.clientX+10)+'px','top':''+(e.clientY+10)+'px'}).on('click','a',function(){
				 var dsId = $("base").attr("dsId");
				if($(this).text() == '加入梳理模型'){
					var rawType = 'fm';
					 modelId = dsId;
					  var condList = new Array();
				      condList.push(modelId);
				      condList.push(id);
				      $.ajax({  
			  		       type: "post",  
			  		       url:base+"/rest/dataModel/sendToModel",  
			  		       data:{"condList":condList,"rawType":rawType},
			  		       dataType:"json",
			  		       traditional: true,//这里设置为true
			  		       success:function(result) { 
			  		    	   if(result.msgCode == 0){
			  		    		   layer.alert("发送成功!");
			  		    	   }else{
			  		    		 layer.alert(result.msg);
			  		    	   }
			  		       }
		 		      })
				}else if($(this).text() == '浏览数据'){
					var tabname ='浏览数据@'+qTableName;
		    		var this_id = id+"浏览数据";
		    		var url = base+"/browser/data?tableName="+qTableName+"&dsId="+dsId;
		      		parent.parent.addTab(tabname,url,this_id);
				}else if($(this).text() == 'SQL查询'){
					var tabname ='SQL查询@'+qTableName;
		    		var this_id = id+"SQL查询";
		    		var url = base+"/browser/sqlQuery?dsId="+dsId+"&table="+qTableName;
		    		parent.parent.addTab(tabname,url,this_id);
				}
			})
			
	}
	

	*/
	
	if(cellView.model.attributes.type == "bpmn.Choreography"){
		console.log(cellView);
		var list = [];
		var currentElement = cellView.model;
		list.push(currentElement.id);
		/*var NeighborsBPMNArr = graph.getNeighbors(currentElement);
		list = NeighborsBPMNArr;
		$.each(NeighborsBPMNArr,function(i,v){
			console.log(v.id) 
			if(!list.contains(v)){
			 NeighborsBPMNArr = graph.getNeighbors(v);
			 $.each(NeighborsBPMNArr,function(i,v){
				 
			 }
			}
		})*/
		findRelateModel(currentElement);
		console.log(list);
		function findRelateModel(currentElement){
				 var NeighborsBPMNArr = graph.getNeighbors(currentElement);
				 $.each(NeighborsBPMNArr,function(i,v){
						console.log(v.id) 
						if(list.indexOf(v.id) == -1){
							list.push(v.id)
							findRelateModel(v);
						}
					})
		}
	
		  var e = evt || window.evt;
		//移除其他的列表
		$('.item_ul').remove();
		var removeIndex = 6;
	    //一级的ul 
		var iconArray = [];
		var fa_item_ul = $('<ul class="vakata-context jstree-contextmenu jstree-default-contextmenu item_ul"></ul>');
		var fa_item_li;//一级的li
		if(rawType != "CLUSTING_SUB"){
			iconArray = ["iconfont icon-icon-chakanxq"," iconfont icon-SQL","iconfont icon-tianjia1","iconfont icon-tongbubiaojiegou","icon-share","iconfont icon-juxing2","","",""];
			fa_item_li = ['浏览数据','SQL查询','创建表复制流程','表结构变化检查','表级血缘分析','字段血缘分析','发送到','相关对象发送到','全部相关对象发送到'];  //一级的li
			if(cellView.model.attributes.attrs.objectType === 'sql'){
				fa_item_li.splice(3, 1);
				iconArray.splice(3, 1);
				removeIndex-- ;
			}
		}else{
			iconArray =  ["iconfont icon-icon-chakanxq"," iconfont icon-SQL","iconfont icon-tianjia1","iconfont icon-tongbubiaojiegou","icon-share","iconfont icon-juxing2"];
			fa_item_li = ['浏览数据','SQL查询','创建表复制流程','表结构变化检查','表级血缘分析','字段血缘分析']; //一级的li
			if(cellView.model.attributes.attrs.objectType === 'sql'){
				fa_item_li.splice(3, 1);
				iconArray.splice(3, 1);
				removeIndex-- ;
			}
			
		}
		
		
		var fa_item_second_li;  //一级列表的值
		var endableSendModel;
		var isRequest = true;
		$.each(fa_item_li,function(i,v){			//遍历一级列表
			//添加二级菜单
			var showMenuSize =  removeIndex -1 ;
			if(i> showMenuSize){
					fa_item_ul.append('<li class="oneMenuLi  send"><i class="'+iconArray[i]+'"></i><a class="erFisrtMenu" href="#">'+v+'</a></li>');	
				
					if(rawType == "fm"){
						var data = {modelId : null,modelName : '梳理模型'};
						fa_item_second_li = [data];
					}else  if(rawType == "cm"){
						//fa_item_second_li = ['加为梳理模型'];
						if(isRequest){
							$.ajax({  
			    		       type: "post",  
			    		       url:base+"/rest/dataModel/enableModel",  
			    		       data:{"dsId":dsId,"rawType":rawType,"modelId":modelId},
			    		       dataType:"json",
			    		       async: false,
			    		       success:function(result) { 
			    		    	   if(result.msgCode == 0){
			    		    		   endableSendModel = result.data
			    		    	   }else{
			    		    		 layer.alert(result.msg);
			    		    	   }
			    		       }
			    	      })
				    	   isRequest = false; 
						}
			  			if(endableSendModel != null){
			  			  if(endableSendModel.length>0){
    		    			  fa_item_second_li = endableSendModel;	
    		    		  }else{
    		    			  fa_item_ul.children("li:eq("+removeIndex+")").remove();
    		    		  }
			  			} 
					}
			}else{
				fa_item_ul.append('<li class=""><a class="" href="#"><i class="'+iconArray[i]+'"></i>'+v+'</a></li>')	
			}
		});
		
		fa_item_ul.appendTo($('#app'));				//加载一级列表
		
		var item_ul_width = $('.item_ul').outerWidth(true)
		
		var fa_item_second_ul = $('<ul class="vakata-context jstree-contextmenu jstree-default-contextmenu item_second_ul itemNone"></ul>')
		$.each(fa_item_second_li,function(i,v){
			$(fa_item_second_ul).append('<li><a href="#" class="ersecondMenu" modelId='+v.modelId+'>'+v.modelName+'</a></li>')
		})
		
		$('.send').append(fa_item_second_ul)	//加载二级列表

		$('.oneMenuLi').hover(function(){           //一级 列表的数据经过事件
			$(this).children('.erFisrtMenu').addClass('vakataActive')
			$(this).siblings().removeClass('vakataActive')
			$(this).children('.item_second_ul').removeClass('itemNone')
		},function(){
			$(this).children('.item_second_ul').addClass('itemNone')
			$(this).children('.erFisrtMenu').removeClass('vakataActive')
			$(this).children('.item_second_ul').addClass('itemNone')
		})
		
		
		$('.item_ul').css({'display':'block','position':'absolute','z-index':'1000','background':'#fff','left':''+(e.clientX+10)+'px','top':''+(e.clientY+10)+'px'})
		$('.item_second_ul').css({'display':'block','position':'absolute','z-index':'1000','background':'#fff','left':''+item_ul_width-3+'px','top':'2px'})	//两个列表的样式
	
		var id = cellView.model.id;
			var qTableName = cellView.model.attributes.qTableName;
			if(!qTableName){
				qTableName=  cellView.model.attributes.participants[0];
			}
			fa_item_ul.appendTo($('#app'));
			$('.item_ul').css({'display':'block','position':'absolute','z-index':'1000','background':'#fff','left':''+(e.clientX+10)+'px','top':''+(e.clientY+10)+'px'}).on('click','a',function(){
				 var dsId = $("base").attr("dsId");
				 if($(this).hasClass('ersecondMenu')){
					var type = $(this).parent().parent().siblings('a').text();
					 var model_Id = $(this).attr("modelId");
					if(type == '发送到'){
							var id = cellView.model.id;
							sendToModel(id,model_Id);
					}else if (type == '相关对象发送到'){
						var id = cellView.model.id;
						//当前表id，关联表id,cellView
						sendToModelRelate(id,model_Id,cellView);
					}else if(type == '全部相关对象发送到'){
						var list = [];       //定义所有的相邻元素id的集合,包括自身
						var currentElement = cellView.model
						list.push(currentElement.id);  
						findRelateModel(currentElement);
						console.log(list);
						function findRelateModel(currentElement){
								 var NeighborsBPMNArr = graph.getNeighbors(currentElement);
								 $.each(NeighborsBPMNArr,function(i,v){
										console.log(v.id) 
										if(list.indexOf(v.id) == -1){
											list.push(v.id)
											findRelateModel(v);
										}
									})
						}
						sendToModelAllRelate(model_Id,list);
					}
					
				 }else{
					 if($(this).text() == '梳理模型'){
							var rawType = 'fm';
							 modelId = dsId;
							  var condList = new Array();
						      condList.push(modelId);
						      condList.push(id);
						      $.ajax({  
					  		       type: "post",  
					  		       url:base+"/rest/dataModel/sendToModel",  
					  		       data:{"condList":condList,"rawType":rawType},
					  		       dataType:"json",
					  		       traditional: true,//这里设置为true
					  		       success:function(result) { 
					  		    	   if(result.msgCode == 0){
					  		    		   layer.alert("发送成功!");
					  		    	   }else{
					  		    		 layer.alert(result.msg);
					  		    	   }
					  		       }
				 		      })
						}else if($(this).text() == '浏览数据'){
							var id = cellView.model.id;
							var tabname ='浏览数据@'+qTableName;
				    		var this_id = id+"浏览数据";
				    		var url = base+"/browser/data?tableName="+qTableName+"&dsId="+dsId+"&objectId="+id;
				      		parent.parent.addTab(tabname,url,this_id);
						}else if($(this).text() == 'SQL查询'){
							var id = cellView.model.id;
							var tabname ='SQL查询@'+qTableName;
				    		var this_id = id+"SQL查询";
				    		var url = base+"/browser/sqlQuery?dsId="+dsId+"&tableId="+id;
				    		parent.parent.addTab(tabname,url,this_id);
						}else if($(this).text() == '创建表复制流程'){
							var id = cellView.model.id;
			  		    		$.ajax({
			  		    			url:'/rest/simpleDxflow/findObjforInput',
			  		    			data:{"objectId":id},
			  		    			type:"GET",
			  		    			success:function(res){
			  		    				if(res.code == 0){
			  		    					if(res.object == true){
			  		    						parent.layer.confirm("该对象已被交换流程使用,是否继续？",{
			  		    							btn:['是','否'],
			  		    							yes:function(index, layero){
			  		    								parent.layer.close(index);
			  		    								renderDxflowPage(dsId,id)
			  		    							},
			  		    							btn2:function(index, layero){
			  		    								parent.layer.close(index);
			  		    							}
			  		    						})
			  		    					}else{
			  		    						renderDxflowPage(dsId,id)
			  		    					}
			  		    				}else{
			  		    					parent.layer.alert(res.msg);
			  		    				}
			  		    			}
			  		    		})
			  		    		
							
						}else if($(this).text() == '表结构变化检查'){
		  		    		var id = cellView.model.id;
		  		    		var objectType =  cellView.model.attributes.attrs.objectType;
		  		    		
				    		parent.layer.open({
				    	        type: 2,//弹出框类型
				    	        title: '检查表结构变化',
				    	        shadeClose: false, //点击遮罩关闭层
				    	        area : ['900px' , '600px'],
				    	        btn:['同步变化',"关闭"],
				    	        content:['/page/cobming/compareChangeDataObj?dsId='+dsId+'&objectId='+id+'&objectType\='+objectType+'&type=changeTable'],
				    	        	//[base+"/rest/dataModel/singleTableCompare?dsId="+dsId+"&objectId="+objectId+"&rawType="+rawType] //将结果页面放入layer弹出层中
				    	        yes:function(index,layer){
				    	          	 $.ajax({  
						 		         type: "GET",  
						 		         url:"/rest/dataModel/synCompareDataObj",  
						 		         data:{"dsId":dsId,"objectId":objectId,"objectType":objectType},
						 		         success:function(result) { 
						 		        	parent.layer.alert(result.msg)
						 		         }
						 		     }) 
						        	return false;
				    	        }
				    	    });
						}else if($(this).text() == '表级血缘分析'){
							var id = cellView.model.id;
							var tableName = cellView.model.attributes.attrs.tableName;
		  		    		
		  		    		var tabname ='表血缘分析@'+tableName;
				    		var this_id = id+"表血缘分析";
				    		var url = base+"/browser/dataRelation?objectId="+id;
				    		parent.parent.addTab(tabname,url,this_id);
						}else if($(this).text() == '字段血缘分析'){
							var id = cellView.model.id;
							var tableName =  cellView.model.attributes.attrs.tableName;
		  		    		var tabname ='字段关系@'+tableName;
				    		var this_id = id+"字段关系";
				    		var url = base+"/browser/fieldRelationEr?objectId="+id;
				    		parent.parent.addTab(tabname,url,this_id);
						}
				 }
				
			})
	}

})

paper.on('blank:contextmenu',function(){//右键删除列表		
	$('.item_ul').remove()
})



$(document).click(function(e){	//点击doucment删除列表
	 var tar = $(e.target);
	 if(!tar.hasClass('erFisrtMenu')){
		 $('.item_ul').remove()
	 }
	
})

function sendToModel(id,model_Id){
	  if(rawType == 'fm'){
    	  //就是这个格式
		  model_Id = dsId;
      }
	 var condList = new Array();
     condList.push(model_Id);
     condList.push(id);
     $.ajax({  
		       type: "post",  
		       url:base+"/rest/dataModel/sendToModel",  
		       data:{"condList":condList,"rawType":rawType},
		       dataType:"json",
		       traditional: true,//这里设置为true
		       success:function(result) { 
		    	   if(result.msgCode == 0){
		    		   layer.alert("发送成功!");
		    	   }else{
		    		 layer.alert(result.msg);
		    	   }
		       }
      })
}

function sendToModelRelate(id,model_Id,cellView){
	  if(rawType == 'fm'){
    	  //就是这个格式
		  model_Id = dsId;
      }
	 var condList = new Array();
     condList.push(model_Id);
     condList.push(id);
     var NeighborsBpmnArr = graph.getNeighbors(cellView.model)
 	 $.each(NeighborsBpmnArr,function(i,v){
 		condList.push(v.id);
 	 })
   
     $.ajax({  
		       type: "post",  
		       url:base+"/rest/dataModel/sendToModel",  
		       data:{"condList":condList,"rawType":rawType},
		       dataType:"json",
		       traditional: true,//这里设置为true
		       success:function(result) { 
		    	   if(result.msgCode == 0){
		    		   layer.alert("发送成功!");
		    	   }else{
		    		 layer.alert(result.msg);
		    	   }
		       }
      })
}
function sendToModelAllRelate(model_Id,list){
	if(rawType == 'fm'){
  	  //就是这个格式
		  model_Id = dsId;
    }
	 var condList = new Array();
   condList.push(model_Id);
   //condList.push(list);
	 $.each(list,function(i,v){
		condList.push(v);
	 })
   $.ajax({  
		       type: "post",  
		       url:base+"/rest/dataModel/sendToModel",  
		       data:{"condList":condList,"rawType":rawType},
		       dataType:"json",
		       traditional: true,//这里设置为true
		       success:function(result) { 
		    	   if(result.msgCode == 0){
		    		   layer.alert("发送成功!");
		    	   }else{
		    		 layer.alert(result.msg);
		    	   }
		       }
    })
}
function renderDxflowPage(dsId,id){
	$.ajax({
		url:'/rest/dxflowDesign/findBizBydsId',
		data:{"dsId":dsId},
		type:"GET",
		success:function(res){
			var data = res.data;
			var html = '<div class="layer-content form-body"><div class="mt-radio-list">';
			for(var i=0;  i < data.length; i++){
				html += " <label class='mt-radio mt-radio-outline'>" + data[i].dxBiztypeName;
				if(i != 0){
					html +=  "  <input type='radio' id='bizType'   name='bieType' value='"+data[i].bizTypeId+"' bizTypeId='"+data[i].bizTypeId+"' url='"+data[i].guideUrl+"' bizTypeName='"+data[i].dxBiztypeName+"' />";
				}else{
					html +=  "<input type='radio' checked='checked'  id='bizType'  name='bieType'  value='"+data[i].bizTypeId+"' bizTypeId='"+data[i].bizTypeId+"' url='"+data[i].guideUrl+"'  bizTypeName='"+data[i].dxBiztypeName+"' />";
				} 
				html += "<span></span></label>"
			}
			html += '</div></div>';
			if(res.code == 0 ){
				parent.layer.open({
                    type : 1,
                    content :html,
                    area: ['470px', '240px'],
                    maxmin : true,
                    btn:["下一步"],
                    title : "选择流程业务类型",
                    yes:function(index,layero){
                    	parent.layer.close(index);
                    	var bizId = $(parent.document).find("input[name='bieType']:checked").val();
                		var url =  $(parent.document).find("input[name='bieType']:checked").attr('url');
                		var bizTypeName = $(parent.document).find("input[name='bieType']:checked").attr('bizTypeName');
                    	parent.layer.open({
    	                    type : 2,
    	                    content : [ url + '?bizId=' + bizId + '&bizTypeName=' + bizTypeName+ '&objectId='+id],
    	                    area: ['900px', '600px'],
    	                    maxmin : true,
    	                    title : "单表复制",
    	                    
    	                });
                    }
                    
                });
			}
		}
	})
}

